package com.wits.platform.common.utils;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

import com.wits.platform.entity.BaseEntity;

public class ExportExcelUtil<T extends BaseEntity> {
	
	private static final String DEFAULT_TITLE="报表";

	public void exportExcel(String[] headers,String[]fieldNames,Collection<T> dataset,OutputStream out) {
		exportExcel(DEFAULT_TITLE, headers,fieldNames,dataset, out, "yyyy-MM-dd");
	}

	public void exportExcel(String[] headers,String[]fieldNames, Collection<T> dataset,OutputStream out, String pattern) {
		exportExcel(DEFAULT_TITLE, headers,fieldNames,dataset, out, pattern);
	}

	/**
	 * 
	 * @param title
	 *            表格标题
	 * @param headers
	 *            表格属性列名数组
	 * @param dataset
	 *            需要显示的数据集合
	 * @param out
	 *            与输出设备关联的流对象，可以将 EXCEL文档导出到本地文件或者网络中
	 * @param pattern
	 *            如果有时间数据，设定输出格式。默认为 "yyy-MM-dd"
	 */
	@SuppressWarnings("unchecked")
	public void exportExcel(String title, String[] headers,String[] fieldNames,Collection<T> dataset, OutputStream out, String pattern) {

		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();

		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);

		// 设置表格默认列宽度为 15 个字节
		sheet.setDefaultColumnWidth(15);

		//设置样式
		HSSFCellStyle style = workbook.createCellStyle();
		style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

		// 设置字体
		HSSFFont font = workbook.createFont();
		font.setColor(HSSFColor.VIOLET.index);
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setFont(font);

		//设置样式
		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
		style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

		//设置字体
		HSSFFont font2 = workbook.createFont();
		font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		style2.setFont(font2);

		//表格标题
		HSSFRow row = sheet.createRow(0);
		for (int i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellStyle(style);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}

		//产生数据
		int index=0;
		for(Iterator<T> iter=dataset.iterator();iter.hasNext();){
			index++;
			row = sheet.createRow(index);
			T t=(T)iter.next();
			
			for (int i = 0; i < fieldNames.length; i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellStyle(style2);
				String fieldName = fieldNames[i];

				String getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
				try {
					Class tCls = t.getClass();
					Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
					Object value = getMethod.invoke(t, new Object[] {});
					String textValue = null;
					if (value instanceof Collection) {
						Collection collection = (Collection) value;
						Object obj = null;
						StringBuffer sb = new StringBuffer();
						for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
							obj = iterator.next();
							if (obj instanceof BaseEntity) {
								sb.append(((BaseEntity) obj).display()).append(",");
							} else {
								sb.append(obj.toString()).append(",");
							}
						}
						
						if (sb.length()>0 && sb.charAt(sb.length() - 1) == ',') {
							sb.deleteCharAt(sb.length() - 1);
						}
						textValue = sb.toString();
					}else if (value instanceof Date) {
						Date date = (Date) value;
						textValue = DateUtil.format(date,pattern);
					}else {
						textValue =value!=null? value.toString():"";
					}

					if (textValue != null) {
						Pattern p = Pattern.compile("^//d+(//.//d+)?$");
						Matcher matcher = p.matcher(textValue);
						if (matcher.matches()) {
							// 是数字当作 double 处理
							cell.setCellValue(Double.parseDouble(textValue));
						} else {
							HSSFRichTextString richString = new HSSFRichTextString(textValue);
							HSSFFont font3 = workbook.createFont();
							font3.setColor(HSSFColor.BLUE.index);
							richString.applyFont(font3);
							cell.setCellValue(richString);
						}

					}

				} catch (Exception e) {
					e.printStackTrace();

				}finally {
					// clear
				}

			}
		}

		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}